<template>
  <div class="user-list-container">
    <!-- 搜索栏-->
    <div class="search-bar">
      <!-- 独立用户名搜索 -->
      <el-input
        v-model="searchParams.username"
        placeholder="用户名"
        clearable
        style="width: 180px"
        @keyup.enter="handleSearch"
      />

      <!-- 独立昵称搜索 -->
      <el-input
        v-model="searchParams.nickname"
        placeholder="昵称"
        clearable
        style="width: 180px; margin-left: 10px"
        @keyup.enter="handleSearch"
      />

      <!-- 独立手机号搜索 -->
      <el-input
        v-model="searchParams.phone"
        placeholder="手机号"
        clearable
        style="width: 180px; margin-left: 10px"
        @keyup.enter="handleSearch"
      />

      <!-- 独立邮箱搜索 -->
      <el-input
        v-model="searchParams.email"
        placeholder="邮箱"
        clearable
        style="width: 220px; margin-left: 10px"
        @keyup.enter="handleSearch"
      />

      <!-- 保持状态和角色筛选 -->
      <el-select
        v-model="searchParams.status"
        placeholder="状态"
        clearable
        style="width: 120px; margin-left: 10px"
      >
        <el-option label="启用" :value="1" />
        <el-option label="禁用" :value="2" />
      </el-select>

      <el-select
        v-model="searchParams.roleType"
        placeholder="角色"
        clearable
        style="width: 140px; margin-left: 10px"
      >
        <el-option label="管理员" :value="1" />
        <el-option label="广告用户" :value="2" />
        <el-option label="设备机构" :value="3" />
      </el-select>

      <el-button type="primary" @click="handleSearch" style="margin-left: 10px">
        搜索
      </el-button>
      <el-button type="success" @click="handleAdd" style="margin-left: 10px">
        新增
      </el-button>
    </div>

    <el-table :data="tableData.records" style="width: 100%" border stripe>
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="username" label="用户名" width="120" />
      <el-table-column prop="nickname" label="昵称" width="120">
        <template #default="{ row }">
          {{ row.nickname || "--" }}
        </template>
      </el-table-column>

      <el-table-column prop="roleType" label="角色" width="120">
        <template #default="{ row }">
          <el-tag :type="roleTagType(row.roleType)">
            {{ formatRole(row.roleType) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="phone" label="手机号" width="150">
        <template #default="{ row }">
          {{ row.phone || "--" }}
        </template>
      </el-table-column>

      <el-table-column prop="email" label="邮箱" width="200">
        <template #default="{ row }">
          {{ row.email || "--" }}
        </template>
      </el-table-column>

      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? "启用" : "禁用" }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="createdTime" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatTime(row.createdTime) }}
        </template>
      </el-table-column>

      <el-table-column prop="updatedTime" label="更新时间" width="180">
        <template #default="{ row }">
          {{ formatTime(row.updatedTime) }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="150" fixed="right">
        <template #default="{ row }">
          <el-button size="small" type="primary" @click="handleEdit(row)"
            >编辑</el-button
          >
          <el-button size="small" type="danger" @click="handleDelete(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      v-model="editDialogVisible"
      title="用户管理"
      width="600px"
      @close="activeTab = 'basic'"
    >
      <el-tabs v-model="activeTab">
        <!-- 基本资料 -->
        <el-tab-pane label="基本资料" name="basic">
          <el-form
            ref="basicFormRef"
            :model="basicForm"
            :rules="basicRules"
            label-width="100px"
          >
            <el-form-item label="用户名" prop="username">
              <el-input v-model="basicForm.username" />
            </el-form-item>
            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="basicForm.nickname" />
            </el-form-item>
            <el-form-item label="角色" prop="roleType">
              <el-select v-model="basicForm.roleType">
                <el-option label="管理员" :value="1" />
                <el-option label="广告用户" :value="2" />
                <el-option label="设备机构" :value="3" />
              </el-select>
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="basicForm.phone" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="basicForm.email" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitBasic"
                >保存修改</el-button
              >
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 修改密码 -->
        <el-tab-pane label="修改密码" name="password">
          <el-form
            ref="passwordFormRef"
            :model="passwordForm"
            :rules="passwordRules"
            label-width="100px"
          >
            <el-form-item label="新密码" prop="password">
              <el-input
                v-model="passwordForm.password"
                type="password"
                show-password
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitPassword"
                >修改密码</el-button
              >
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 状态管理 -->
        <el-tab-pane label="账户状态" name="status">
          <el-form
            ref="statusFormRef"
            :model="statusForm"
            :rules="statusRules"
            label-width="100px"
          >
            <el-form-item label="账户状态" prop="status">
              <el-select v-model="statusForm.status">
                <el-option label="启用" :value="1" />
                <el-option label="禁用" :value="2" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitStatus"
                >更新状态</el-button
              >
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <el-dialog
      v-model="addDialogVisible"
      title="新增用户"
      width="500px"
      @close="resetAddForm"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="addForm.nickname" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" type="password" show-password />
        </el-form-item>
        <el-form-item label="角色" prop="roleType">
          <el-select v-model="addForm.roleType">
            <el-option label="管理员" :value="1" />
            <el-option label="广告用户" :value="2" />
            <el-option label="设备机构" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="addForm.phone" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="addForm.status">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="submitLoading"
          @click="handleAddSubmit"
          >确定</el-button
        >
      </template>
    </el-dialog>
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :total="tableData.total"
        layout="total, prev, pager, next, jumper"
        @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  userList,
  userEdit,
  userDelete,
  userAdd,
  userPassword,
  userStatus,
} from "@/api/userControl";

// 角色映射常量需要定义
const roleMap = {
  1: "管理员",
  2: "广告用户",
  3: "设备拥有机构",
};
// 表格数据
const tableData = ref({
  records: [],
  total: 0,
});
// 搜索参数
const searchParams = ref({
  username: "",
  nickname: "",
  phone: "",
  email: "",
  status: null,
  roleType: null,
});
// 分页参数
const currentPage = ref(1);
const pageSize = ref(10);
const searchKeyword = ref("");
const loading = ref(false);
// 编辑对话框
const editDialogVisible = ref(false);
const activeTab = ref("basic");
const basicFormRef = ref(null);
const passwordFormRef = ref(null);
const statusFormRef = ref(null);
const submitLoading = ref(false); 
const basicForm = ref({
  id: "",
  username: "",
  nickname: "",
  roleType: null,
  phone: "",
  email: "",
});

const passwordForm = ref({
  id: "",
  password: "",
});

const statusForm = ref({
  id: "",
  status: 1,
});
// 新增对话框
const addDialogVisible = ref(false);
const addFormRef = ref(null);
const addForm = ref({
  username: "",
  nickname: "",
  password: "",
  roleType: null,
  phone: "",
  email: "",
  status: 1,
});
// 基本资料验证规则
const basicRules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
  ],
  phone: [
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  email: [{ type: "email", message: "请输入正确的邮箱地址", trigger: "blur" }],
};

// 密码修改验证规则
const passwordRules = {
  password: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { min: 6, message: "密码长度至少6位", trigger: "blur" },
  ],
};

// 状态修改验证规则
const statusRules = {
  status: [{ required: true, message: "请选择状态", trigger: "change" }],
};
// 新增表单验证规则
const formRules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
  ],
  nickname: [{ required: true, message: "请输入昵称", trigger: "blur" }],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, message: "密码长度至少6位", trigger: "blur" },
  ],
  roleType: [{ required: true, message: "请选择角色", trigger: "change" }],
  phone: [
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  email: [{ type: "email", message: "请输入正确的邮箱地址", trigger: "blur" }],
  status: [{ required: true, message: "请选择状态", trigger: "change" }],
};
// 初始化加载数据
onMounted(() => {
  loadUsers();
});

const loadUsers = async () => {
  try {
    loading.value = true;
    const { data } = await userList(
      currentPage.value,
      pageSize.value,
      searchParams.value
    );
    console.log(data);
    // 根据接口返回结构更新数据
    tableData.value = {
      records: data.data.records,
      total: data.data.total,
    };
  } catch (error) {
    ElMessage.error("获取用户列表失败");
    console.error("接口错误:", error);
  } finally {
    loading.value = false;
  }
};

// 分页大小变化处理
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  loadUsers();
};

// 编辑处理
const handleEdit = (row) => {
  basicForm.value = {
    id: row.id,
    username: row.username,
    nickname: row.nickname,
    roleType: row.roleType,
    phone: row.phone,
    email: row.email,
  };

  statusForm.value = {
    id: row.id,
    status: row.status === 1 ? "启用" : "禁用",
  };

  passwordForm.value = {
    id: row.id,
    password: "",
  };

  editDialogVisible.value = true;
  activeTab.value = "basic";
};

// 提交编辑表单
const submitBasic = async () => {
  try {
    await basicFormRef.value.validate();
    const { data } = await userEdit(basicForm.value);
    if (data.code === 200) {
      ElMessage.success("基本资料更新成功");
      loadUsers();
    }
  } catch (error) {
    ElMessage.error(error.message || "更新失败");
  }
};

const submitPassword = async () => {
  try {
    await passwordFormRef.value.validate();
    const { data } = await userPassword(
      passwordForm.value.id,
      passwordForm.value.password
    );
    if (data.code === 200) {
      ElMessage.success("密码修改成功");
      passwordForm.value.password = "";
    }
  } catch (error) {
    ElMessage.error(error.message || "密码修改失败");
  }
};

const submitStatus = async () => {
  try {
    const statusValue = Number(statusForm.value.status);
    await ElMessageBox.confirm(
      `确认将用户状态修改为 ${statusValue === 1 ? '启用' : '禁用'} 吗？`,
      '操作确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    const { data } = await userStatus(statusForm.value.id, statusValue);
    if (data.code === 200) {
      ElMessage.success("状态更新成功");
      editDialogVisible.value = false;
      loadUsers();
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || "状态更新失败");
    }
  }
};
// 搜索处理
const handleSearch = () => {
  currentPage.value = 1;
  loadUsers();
  console.log("当前搜索参数：", {
    username: searchParams.value.username,
    nickname: searchParams.value.nickname,
    phone: searchParams.value.phone,
    email: searchParams.value.email,
    status: searchParams.value.status,
    roleType: searchParams.value.roleType,
  });
};
const handlePageChange = (newPage) => {
  currentPage.value = newPage;
  // 这里添加分页请求逻辑
  // loadUsers()
};
// 修改现有的 handleDelete 方法
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除用户 ${row.username} ?`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        await userDelete(row.id);
        ElMessage.success("删除成功");
        loadUsers();
      } catch (error) {
        ElMessage.error("删除失败");
      }
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

// 打开新增对话框
const handleAdd = () => {
  addDialogVisible.value = true;
};

// 重置新增表单
const resetAddForm = () => {
  if (addFormRef.value) {
    addFormRef.value.resetFields();
  }
  addForm.value = {
    username: "",
    nickname: "",
    password: "",
    roleType: null,
    phone: "",
    email: "",
    status: 1,
  };
};

// 提交新增表单
const handleAddSubmit = async () => {
  if (!addFormRef.value) return;

  try {
    await addFormRef.value.validate();
    submitLoading.value = true;

    const submitData = { ...addForm.value };
    // 删除可能存在的空字段
    delete submitData.createdTime;
    delete submitData.updatedTime;

    const { data } = await userAdd(submitData);

    if (data.code === 200) {
      ElMessage.success("新增成功");
      addDialogVisible.value = false;
      loadUsers(); // 刷新列表
    } else {
      ElMessage.error(data.message || "新增失败");
    }
  } catch (error) {
    console.error("新增用户失败:", error);
    ElMessage.error(error.message || "新增失败");
  } finally {
    submitLoading.value = false;
  }
};

// 角色标签类型方法
const roleTagType = (roleType) => {
  const types = {
    1: "danger",
    2: "primary",
    3: "warning",
  };
  return types[roleType] || "info";
};
// 格式化角色
const formatRole = (roleType) => {
  return roleMap[roleType] || "未知角色";
};
// 格式化时间
const formatTime = (time) => {
  if (!time) return "--";
  return new Date(time).toLocaleString();
};
</script>

<style scoped>
.search-bar {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
}
.user-list-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>